package cn.nb12.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.Gson;

public class Main {
	private static Gson gson=new Gson();
	public static void main(String[] args) throws IOException, InterruptedException {
		File file1=new File("D:\\user\\xbox.txt");
		File file2=new File("D:\\user\\xbox2.txt");
		try {
			file2.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		FileReader reader=null;
		FileWriter ss=null;
		try {
			ss=new FileWriter(file2);
			reader=new FileReader(file1);
			BufferedReader reader2=new BufferedReader(reader);
			String temp=null;
			StringBuffer str=new StringBuffer();
			BufferedWriter writer=new BufferedWriter(ss);
			while ((temp=reader2.readLine())!=null) {
				String[] split = temp.split(":");
				Map<String,Object> param=new HashMap<>();
				param.put("kw", split[4]);
				Thread.sleep(10);
				String sendPost = sendPost("http://fanyi.baidu.com/sug", param, "UTF-8");
				JsonRootBean fromJson = gson.fromJson(sendPost, JsonRootBean.class);
				if(fromJson!=null) {
					append(str, fromJson, split);
				}
				else {
					System.out.println("返回结果为空");
					Thread.sleep(5000);
					String result = sendPost("http://fanyi.baidu.com/sug", param, "UTF-8");
					fromJson = gson.fromJson(result, JsonRootBean.class);
					append(str, fromJson, split);
				}
				
			}
			writer.write(str.toString());
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			ss.close();
			reader.close();
		}
		
	}
	
	public static void append(StringBuffer buf,JsonRootBean fromJson,String[] split) {
		if(fromJson!=null) {
			if(fromJson.getErrno()==0) {
				buf.append(String.format("编号：%s，全称：%s，中文名称：%s\r\n", split[0],split[4],fromJson.getData().get(0).getV()));
			}
			else {
				buf.append(String.format("编号：%s，全称：%s，中文名称：%s\r\n", split[0],split[4],"没有找到翻译"));
			}
		}
		else {
			buf.append(String.format("编号：%s，全称：%s，中文名称：%s\r\n", split[0],split[4],"没有找到翻译"));
		}
		
	}
	
	public static  int toNumber(String str) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			return 0;
		}
	}
	
	/** 
     * @Description:使用HttpURLConnection发送post请求 
     * @author:liuyc 
     * @time:2016年5月17日 下午3:26:07 
     */  
    public static String sendPost(String urlParam, Map<String, Object> params, String charset) {  
        StringBuffer resultBuffer = null;  
        // 构建请求参数  
        StringBuffer sbParams = new StringBuffer();  
        if (params != null && params.size() > 0) {  
            for (Entry<String, Object> e : params.entrySet()) {  
                sbParams.append(e.getKey());  
                sbParams.append("=");  
                sbParams.append(e.getValue());  
                sbParams.append("&");  
            }  
        }  
        HttpURLConnection con = null;  
        OutputStreamWriter osw = null;  
        BufferedReader br = null;  
        // 发送请求  
        try {  
            URL url = new URL(urlParam);  
            con = (HttpURLConnection) url.openConnection();  
            con.setRequestMethod("POST");  
            con.setDoOutput(true);  
            con.setDoInput(true);  
            con.setUseCaches(false);  
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            if (sbParams != null && sbParams.length() > 0) {  
                osw = new OutputStreamWriter(con.getOutputStream(), charset);  
                osw.write(sbParams.substring(0, sbParams.length() - 1));  
                osw.flush();  
            }  
            // 读取返回内容  
            resultBuffer = new StringBuffer();  
            int contentLength = toNumber(con.getHeaderField("Content-Length"));  
            if (contentLength > 0) {  
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));  
                String temp;  
                while ((temp = br.readLine()) != null) {  
                    resultBuffer.append(temp);  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();
        } finally {  
            if (osw != null) {  
                try {  
                    osw.close();  
                } catch (IOException e) {  
                    osw = null;  
                   e.printStackTrace();
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                    e.printStackTrace();
                } finally {  
                    if (con != null) {  
                        con.disconnect();  
                        con = null;  
                    }  
                }  
            }  
        }  
  
        return resultBuffer.toString();  
    }  
}
